﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Web;
using Excel = Microsoft.Office.Interop.Excel;
using System.Web.UI;

namespace CompanyManagement
{
    public class ExportExcel<T> 
    {

        /// <summary>
        /// Exports to excel.
        /// </summary>
        /// <param name="fileName">Name of the file.</param>
        /// <param name="response">The response.</param>
        /// <param name="columns">The columns.</param>
        /// <param name="objectContextList">The object context list.</param>
        public static void ExportToExcel(string fileName,HttpResponse response,IList<int> columns,List<T> objectContextList)
        {
            response.ContentType = "application/csv";
            response.Charset = "";
            response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.ContentEncoding = Encoding.Unicode;
            response.BinaryWrite(Encoding.Unicode.GetPreamble());
            DataTable dtb = ConvertsDataTable.ConvertToDataTable(objectContextList);
            try
            {
                StringBuilder sb = new StringBuilder();
                IList<int> icolumn = columns;
                int count = 0;
                foreach (var i in icolumn)
                {
                    if (dtb.Columns[i].ColumnName != null)
                    {
                        sb.Append(dtb.Columns[i].ColumnName);
                        if (count < icolumn.Count - 1)
                            sb.Append("\t");
                    }
                    count = count + 1;
                }
                response.Write(sb.ToString() + "\n");
                response.Flush();
                //Append Data
                int soDem = 0;
                while (dtb.Rows.Count >= soDem + 1)
                {
                    sb = new StringBuilder();

                    for (int col = 0; col < icolumn.Count; col++)
                    {
                        if (dtb.Rows[soDem][icolumn[col]] != null)
                            sb.Append(dtb.Rows[soDem][icolumn[col]].ToString().Replace(",", " "));
                        sb.Append("\t");
                    }
                    //if (dtb.Rows[soDem][dtb.Columns.Count - 1] != null)
                    //    sb.Append(dtb.Rows[soDem][dtb.Columns.Count - 1].ToString().Replace(",", " "));

                    response.Write(sb.ToString() + "\n");
                    response.Flush();
                    soDem = soDem + 1;
                }
            }
            catch (Exception ex)
            {
                response.Write(ex.Message);
            }
            dtb.Dispose();
            response.End();
        }
    }
}